package com.lmh.friend.service.user.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lmh.common.core.constants.Constants;
import com.lmh.common.core.domain.TableDataInfo;
import com.lmh.common.core.enums.ResultCode;
import com.lmh.common.core.utils.ThreadLocalUtil;
import com.lmh.common.security.exception.ServiceException;
import com.lmh.friend.domain.exam.Exam;
import com.lmh.friend.domain.exam.dto.ExamDTO;
import com.lmh.friend.domain.exam.dto.ExamQueryDTO;
import com.lmh.friend.domain.exam.vo.ExamVO;
import com.lmh.friend.domain.user.UserExam;
import com.lmh.friend.manager.ExamCacheManager;
import com.lmh.friend.mapper.exam.ExamMapper;
import com.lmh.friend.mapper.user.UserExamMapper;
import com.lmh.friend.service.user.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserExamServiceImpl implements IUserExamService {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamCacheManager examCacheManager;
    @Override
    public int enter(String token, ExamDTO examDTO) {
        // 先对前端传来的examId进行校验，看数据库中是否存在该竞赛
        Exam exam = examMapper.selectById(examDTO.getExamId());
        if (exam == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        //如果竞赛存在，就检查该竞赛是否已经开赛
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_STARTED);
        }
        // 经过上面的检验说明前端传来的参数没有问题
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        // 看该用户是否已经报名了该竞赛
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                        .eq(UserExam::getExamId,examDTO.getExamId())
                        .eq(UserExam::getUserId,userId));
        if (userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        // 将用户的竞赛信息添加到缓存redis中
        examCacheManager.addUserExamCache(userId, exam.getExamId());
        UserExam userExam1 = new UserExam();
        userExam1.setExamId(exam.getExamId());
        userExam1.setUserId(userId);
        return userExamMapper.insert(userExam1);
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        Long total = examCacheManager.getListSize(examQueryDTO.getType(),userId);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            examCacheManager.refreshCache(examQueryDTO.getType(), userId);
            total = new PageInfo<>(examVOList).getTotal();
            if (CollectionUtil.isEmpty(examVOList)) {
                return TableDataInfo.empty();
            }
            return TableDataInfo.success(examVOList, total);
        }else {
            TableDataInfo tableDataInfo = examCacheManager.getExamVOList(examQueryDTO,userId);
            return tableDataInfo;
        }
    }
}
